package config

import (
	"fmt"
	"net/http"
	"sync"

	"github.com/BurntSushi/toml"
)

var (
	dbConfig *Database
	dbOnce   sync.Once
)

type Database struct {
	Schema map[string]db `toml:"mysql"`
}
type db struct {
	Host     string
	Username string
	Password string
	Schema   string
}

func (dma *Database) getTomlFile() string {
	return "mysql.toml"
}

func NewDB() *Database {
	return &Database{}
}

//GetConfig dbConf := conf.NewDatabase().GetConfig()
func (dma *Database) GetConfig() *Database {
	dbOnce.Do(func() {
		if _, err := toml.DecodeFile(TomlPath+dma.getTomlFile(), &dma); err != nil {
			fmt.Println(err)
		}
		dbConfig = dma
	})
	fmt.Println("dbconfig", dbConfig)

	return dbConfig
}

//GetRemoteConfig 读取远程文件 dbConf := conf.NewDatabase().GetRemoteConfig()
func (dma *Database) getRemoteConfig() *Database {
	remotePath := RemoteTomlPath + dma.getTomlFile()
	resp, err := http.Get(remotePath)
	if err != nil {
		fmt.Println(err)
		return dma
	}
	defer resp.Body.Close()
	if _, err := toml.DecodeReader(resp.Body, &dma); err != nil {
		fmt.Println(err)
		return dma
	}
	return dma
}
